<?php
/**
*Baseclass.php 功能:VMI相关处理类
*@date:2017年12月08日
*@author:jiangshilin (894583146@qq.com)
*/
class Vmiclass extends Baseclass
{
    private $host;
    private $apiurl;
    public function __construct(){
        parent::__construct();
    }
    
    //vmi数据写入
    public function addData($data){
        $faildData = array();
        $successData = array();
        $instance=Database::instance('newerp');
        $instance->begin();
        foreach ($data as $key => $info) {
            $stocks = Inventory::get_sku_real_stocks(array($info['sku']), array('warehouse_id'=>$info['warehouseid']));
            $skuInventory['stock'] = !empty($stocks)?$stocks[$info['sku']]:'';
            if(empty($skuInventory) || $skuInventory['stock'] < $info['quantity']){
                $faildData[] = array(
                    'order_id'=>$info['order_id'],
                    'sku'=>$info['sku'],
                    'status'=>-1,
                    'errorinfo'=>'库存不足'
                );
                $instance->rollback();
                return array('faildData'=>$faildData,'successData'=>'');
                break;
           }else{
                $tempdata = array(
                    'order_id'=>$info['order_id'],
                    'sku'=>$info['sku'],
                    'real_stock'=>$skuInventory['stock'],
                    'available_stock'=>$skuInventory['stock']-$info['quantity'],
                    'quantity'=>$info['quantity'],
                    'enterprise_dominant' => $info['enterprise_dominant'],
                    'warehouseid' => $info['warehouseid'],
                );
                $available_order = $this->getAvailableWarehouseorders($info);
                if(!$available_order){
                        $faildData[] = array(
                        'order_id'=>$info['order_id'],
                        'sku'=>$info['sku'],
                        'status'=>-1,
                        'errorinfo'=>'库存不足'
                    );
                    $instance->rollback();
                    return array('faildData'=>$faildData,'successData'=>'');
                    break;
                }
                $deliveryInfo = $this->delivery($info,$available_order);
                $tempdata['deliveryorders'] = $deliveryInfo['deliveryorders'];
                $tempdata['warehouse_data'] = $deliveryInfo['warehouse_data'];               
                $successData[] = $tempdata;
                
           }
        }
        $instance->commit();
        return array('faildData'=>$faildData,'successData'=>$successData);
    }

    //vmi出库操作
    public function delivery($info,$available_order){
        $now = date('Y-m-d H:i:s');
        $quantity = $info['quantity'];
        $sale_price = $info['sale_price'];
        foreach ($available_order as $key => $value) {
           //第一条入库单满足条件
           if($value['warehouse_quantity'] - $value['use_quantity']-$quantity>=0){
                $this->updateWarehouseordersUseQuantity($value['id'],$quantity);
                $warehouse_temp = array('warehouse_man_account'=>$value['warehouse_man_account'],'warehouseorder_id'=>$value['id']); 
                $status = 1; 
                $save_quantity = $quantity;
                
           }else if($value['warehouse_quantity'] - $value['use_quantity']-$quantity<0){
                $tempstock = $value['warehouse_quantity'] - $value['use_quantity'];
                $quantity = $quantity-$tempstock;
                $this->updateWarehouseordersUseQuantity($value['id'],$tempstock);
                $warehouse_temp = array('warehouse_man_account'=>$value['warehouse_man_account'],'warehouseorder_id'=>$value['id']); 
                $status = 2;
                $save_quantity = $tempstock;
                
           }
           $info['supplier_id'] = $value['supplier_id'];
           $info['sku_name'] = $value['sku_name'];
           $info['sku_standard'] = $value['sku_standard'];
           $info['storage_position'] = $value['storage_position'];
           $info['single_price'] = $value['single_price'];
           $info['sale_price'] = $sale_price;
           $info['remark'] = '入库单：'.$value['id'];
           $info['enterprise_dominant'] = $value['enterprise_dominant'];
           $did = $this->addDeliveryorders($info, $now, $save_quantity);
           $real_tax_rate = $this->getTaxRate(array('supplier_id'=>$value['supplier_id'],'sku'=>$info['sku'])); 
           //返回入库单sku储位规格供应商等信息
           $deliveryorders[] = array('deliveryorder_id'=>$did,'warehouseorder_id'=>$value['id'],'supplier_id'=>$value['supplier_id'],'real_tax_rate'=>$real_tax_rate,'single_price'=>$value['single_price'],'quantity'=>
            $save_quantity,'sku_name'=>$value['sku_name'],'sku_standard'=>$value['sku_standard'],'storage_position'=>$value['storage_position'],'export_tax_rebate'=>$value['export_tax_rebate']);
           $warehouse_data[] = array_merge($warehouse_temp,array('deliveryorder_id'=>$did));
           if($status == 1){
                break;
           }else{
                continue;
           }
        }
        return array('deliveryorders'=>$deliveryorders,'warehouse_data'=>$warehouse_data);
    }

    public function addDeliveryorders($info,$now,$quantity){
        //入库单单价
        $single_price = !empty($info['single_price'])?$info['single_price']:0;
        //销售单价
        $sale_price = !empty($info['sale_price'])?$info['sale_price']:0;
        $dedata = array(
            'warehouseid' => $info['warehouseid'],
            'delivery_date' => $now,
            'op_time' => $now,
            'order_id' => !empty($info['order_id'])?$info['order_id']:0,
            'orders_products_id' => !empty($info['orders_products_id'])?$info['orders_products_id']:0,
            'sku' => $info['sku'],
            'quantity' => $quantity,
            'supplier_id' => !empty($info['supplier_id'])?$info['supplier_id']:0,
            'sku_name' => $info['sku_name'],
            'sku_standard' => $info['sku_standard'],
            'storage_position' => $info['storage_position'],
            'single_price' => $sale_price,//销售单价
            'money' => $sale_price*$info['quantity'],//销售金额
            'cost' => $single_price*$info['quantity'],//出库成本
            'type' => !empty($info['type'])?$info['type']:10,//9610正常出库
            'remark' => !empty($info['remark'])?$info['remark']:'',
            'enterprise_dominant' => is_array($info['enterprise_dominant'])?0:$info['enterprise_dominant'],

        );
        $did = DB::insert('deliveryorders',array_keys($dedata))
                        ->values($dedata)
                        ->execute('newerp');
        return $did[0];
    }

    //获取可用的入库单数据
    public function getAvailableWarehouseorders($data){
        $sku = $data['sku'];
        $enterprise_dominant = is_array($data['enterprise_dominant'])?implode($data['enterprise_dominant'],','):intval($data['enterprise_dominant']);
        $warehouseid = intval($data['warehouseid']);
        $sql = "SELECT id,warehouseid,warehouse_quantity,use_quantity,warehouse_man,sku_name,sku_standard,storage_position,supplier_id,single_price,export_tax_rebate,enterprise_dominant 
        FROM warehouseorders 
        WHERE sku='$sku' 
        AND (enterprise_dominant IN ($enterprise_dominant) 
            OR enterprise_dominant=0) 
        AND warehouse_quantity>use_quantity 
        AND warehouseid=$warehouseid 
        ORDER BY enterprise_dominant desc, warehouse_date ASC";
        $res = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
        if(empty($res)) return false;
        $quality = $data['quantity'];
        foreach ($res as $key => $value) {
            $warehouse_man[] = $value['warehouse_man'];
            $tempquality = $value['warehouse_quantity']-$value['use_quantity']-$quality;
            $tempres[] = $value;
            if($tempquality>=0){
                break;
            }
            
        }
        $res = $tempres;
        $ids = implode(',',array_unique($warehouse_man));
        $sql = "SELECT name,id FROM users WHERE id in ($ids)";
        $wman = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array('id');

        foreach ($res as $key => $value) {
            $res[$key]['warehouse_man_account'] = $wman[$value['warehouse_man']]['name'];
        }
        return $res;
    }

    //更新入库单使用数量字段
    public function updateWarehouseordersUseQuantity($id,$use_quantity){
        $sql = "UPDATE warehouseorders SET use_quantity=use_quantity+$use_quantity WHERE id=$id";
        $res = DB::query(Database::UPDATE,$sql)->execute('newerp');
        return $res;
    }

    //获取经销商sku对应加点税
    public function getTaxRate($data){
        $supplier_id = $data['supplier_id'];
        $sku = $data['sku'];
        //加点税
        $sql = "SELECT real_tax_rate FROM vmi_supplier_skus WHERE supplier_id = '$supplier_id' AND sku='$sku'";
        $real_tax_rate = DB::query(Database::SELECT,$sql)->execute('newerp')->get('real_tax_rate');
        return $real_tax_rate;
    }

}